﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
using Calculation = Sunboxsoft.ASMS.Client.Domain.Calculation;
namespace Sunboxsoft.ASMS.Client.UI.Dispatching
{
    /// <summary>
    /// 订单结算
    /// </summary>
    public partial class MaintenanceBillSettlementView : UserControl, IView
    {
        #region Property
        /// <summary>
        /// 维修单号
        /// </summary>
        Guid Id;
        /// <summary>
        /// 维修单详细信息
        /// </summary>
        WebRef.MaintenanceBillDetail billDetail = null;
        Promise _promise = new Promise();
        #endregion

        #region Method
        public MaintenanceBillSettlementView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.TextEditIsFloatNumber(this.txtBalanceAmount, "余额支付", false));
            ValidationManager.Register(this, new Common.Validations.TextEditIsFloatNumber(this.txtUsedCredits, "使用积分", true));
        }
        public MaintenanceBillSettlementView(Guid Id)
            : this()
        {
            this.Id = Id;
        }
        public MaintenanceBillSettlementView(WebRef.MaintenanceBillDetail billDetail)
            : this()
        {
            this.billDetail = billDetail;
        }
        /// <summary>
        /// 绑定结算类型
        /// </summary>
        private void BindSettleMentTypes()
        {
            this.RILookUpEditServiceSettlementTypes.DataSource = Domain.Constant.SettlementTypes.Enumerate(); ;
            this.RILookUpEditServiceSettlementTypes.DisplayMember = "Text";

            this.RILookUpEditGoodsSettleMentTypes.DataSource = Domain.Constant.SettlementTypes.Enumerate();
            this.RILookUpEditGoodsSettleMentTypes.DisplayMember = "Text";
        }
        /// <summary>
        /// 套餐项目操作
        /// </summary>
        private void BindPackageUse()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Code", Type.GetType("System.Int32"));
            dt.Columns.Add("Name", Type.GetType("System.String"));
            DataRow dr1 = dt.NewRow();
            dt.Rows.Add(dr1);
            dr1["Name"] = "使用";
            dr1["Code"] = "1";
            DataRow dr2 = dt.NewRow();
            dr2["Name"] = "不使用";
            dr2["Code"] = "0";
            dt.Rows.Add(dr2);
            this.RILookUpEditUse.DataSource = dt;
            this.RILookUpEditUse.DisplayMember = "Name";
            this.RILookUpEditUse.ValueMember = "Code";
        }
        /// <summary>
        ///加载维修单详细信息
        /// </summary>
        private void LoadBillInfo()
        {
            if (billDetail == null)
            {
                UIContext.Current.InvokeAsync(() =>
                {
                    SingleResult<WebRef.MaintenanceBillDetail> result = new Service.GetService().GetMaintenanceBill(Id);
                    this.BeginInvoke(new Action<SingleResult<WebRef.MaintenanceBillDetail>>((p) =>
                    {
                        if (p.IsSuccess)
                        {
                            billDetail = p.Data;
                            BindBillDetail();
                            _promise.Resolve();
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ShowError(p.Message);
                            _promise.Resolve();
                        }
                    }), result);
                });
            }
            else
            {
                UIContext.Current.InvokeAsync(() =>
               {
                   this.BeginInvoke(new Action(() =>
                  {
                      Id = billDetail.Bill.Id;
                      BindBillDetail();
                      _promise.Resolve();
                  }));
               });
            }
        }
        /// <summary>
        /// 获取客户可用套餐
        /// </summary>
        private void LoadEnabledPackageInstanceList()
        {
            //套餐项目
            List<WebRef.ESettlementBillPackageItem> listPackageItem = new List<WebRef.ESettlementBillPackageItem>();
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.PackageInstanceDetail> result = new Service.QueryService().QueryEnabledPackageInstanceList(
                    ModuleContext.Current.BusinessId.Value,
                    ModuleContext.Current.StationId.Value,
                    billDetail.Bill.CustomerId);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        if (result.Data.Items.Count > 0)
                        {
                            for (int i = 0; i < result.Data.Items.Count; i++)
                            {
                                if (result.Data.Items[i].Items != null)
                                {
                                    for (int j = 0; j < result.Data.Items[i].Items.Length; j++)
                                    {
                                        WebRef.ESettlementBillPackageItem item = new WebRef.ESettlementBillPackageItem(
                                           result.Data.Items[i].Instance.PackageName,
                                            result.Data.Items[i].Items[j].PackageItemName,
                                            result.Data.Items[i].Items[j].PackageItemType,
                                            result.Data.Items[i].Items[j].Value,
                                            result.Data.Items[i].Items[j].PackageItemTagDataType,
                                            result.Data.Items[i].Items[j].PackageItemTagData);

                                        item.PackageInstanceId = result.Data.Items[i].Items[j].PackageInstanceId;
                                        item.PackageInstanceItemId = result.Data.Items[i].Items[j].Id;
                                        item.UseCount = 0;
                                        listPackageItem.Add(item);
                                    }
                                }
                            }
                            this.GCPackageItem.DataSource = null;
                            this.GVPackageItem.FocusedRowHandle = -1;
                            this.GCPackageItem.DataSource = listPackageItem;
                            _promise.Resolve();
                        }
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 获取可用余额
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="assetType"></param>
        /// <returns></returns>
        private decimal GetAsset(Guid Id, int assetType)
        {
            decimal balance = 0;
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<decimal> result = new Service.GetService().GetAsset(Id, assetType);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        balance = result.Data;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
            return balance;
        }
        /// <summary>
        /// 计算应收金额
        /// </summary>
        private void ClacTotalAmount()
        {
            string strMess = "";
            decimal totalActual = Calculation.SettlementBillCalculation.Calc(
                GetListServiceItem() == null ? null : GetListServiceItem().ToArray(),
                GetListMaterial() == null ? null : GetListMaterial().ToArray(),
                GetListPayItem() == null ? null : GetListPayItem().ToArray(),
                GetListPackageItem() == null ? null : GetListPackageItem().ToArray(),
                null,
               Convert.ToDecimal(this.txtBalanceAmount.Text.Trim()), false, out strMess);
            this.lblActualAmount.Text = string.Format("应收金额：{0}={1}", Math.Round(totalActual, 2), strMess);
            this.lblActualAmount.ToolTip = lblActualAmount.Text;
        }
        private void BindBillDetail()
        {
            //电子券
            List<WebRef.ESettlementBillCoupon> listCoupon = new List<WebRef.ESettlementBillCoupon>();
            //商品配件
            List<WebRef.ESettlementBillMaterial> listMaterial = new List<WebRef.ESettlementBillMaterial>();
            //其他付费项目
            List<WebRef.ESettlementBillPayItem> listPayItem = new List<WebRef.ESettlementBillPayItem>();
            //服务项目
            List<WebRef.ESettlementBillServiceItem> listService = new List<WebRef.ESettlementBillServiceItem>();
            this.lblInfo.Text = string.Format("订单编号：{0}-创建时间：{1}", billDetail.Bill.Number, billDetail.Bill.CreatedTime);
            this.txtCustomerInfo.Text = string.Format("{0}-{1}", billDetail.Bill.CustomerName, billDetail.Bill.CustomerTelephone);
            this.ctltxtSalesManagerName.Text = billDetail.Bill.SalesManagerName;
            this.txtCarInfo.Text = string.Format("{0}-{1}-{2}", billDetail.Bill.LPN, billDetail.Bill.VIN, billDetail.Bill.EIN);
            this.txtAmount.Text = billDetail.Bill.Amount.ToString();
            this.lblBalanceAmount.Text = string.Format("可用余额：{0}", GetAsset(billDetail.Bill.CustomerId, Domain.Constant.AssetType.Balance).ToString());
            if (billDetail.ServiceItemList != null)
            {
                for (int i = 0; i < billDetail.ServiceItemList.Length; i++)
                {
                    WebRef.ESettlementBillServiceItem serviceItem = new WebRef.ESettlementBillServiceItem(billDetail.ServiceItemList[i].Id,
                        billDetail.ServiceItemList[i].ServiceItemName,
                        billDetail.ServiceItemList[i].Status);
                    serviceItem.ServiceItemId = billDetail.ServiceItemList[i].ServiceItemId;
                    serviceItem.Price = billDetail.ServiceItemList[i].Price;
                    serviceItem.Hour = billDetail.ServiceItemList[i].Hour;
                    serviceItem.Discount = billDetail.ServiceItemList[i].Discount;
                    serviceItem.Amount = billDetail.ServiceItemList[i].Amount;
                    serviceItem.SettlementType = Domain.Constant.SettlementTypes.ByPay;
                    listService.Add(serviceItem);
                }
            }
            this.GCServiceProject.DataSource = null;
            this.GVServiceProject.FocusedRowHandle = -1;
            this.GCServiceProject.DataSource = listService;
            if (billDetail.MaterialList != null)
            {
                for (int i = 0; i < billDetail.MaterialList.Length; i++)
                {
                    WebRef.ESettlementBillMaterial materialItem = new WebRef.ESettlementBillMaterial(billDetail.MaterialList[i].Id,
                        billDetail.MaterialList[i].MaterialName, billDetail.MaterialList[i].Status);
                    materialItem.MaterialId = billDetail.MaterialList[i].MaterialId;
                    materialItem.Price = billDetail.MaterialList[i].Price;
                    materialItem.Count = billDetail.MaterialList[i].Count;
                    materialItem.Discount = billDetail.MaterialList[i].Discount;
                    materialItem.Amount = billDetail.MaterialList[i].Amount;
                    materialItem.SettlementType = Domain.Constant.SettlementTypes.ByPay;
                    listMaterial.Add(materialItem);
                }
                this.GCGoodsData.DataSource = null;
                this.GVGoodsData.FocusedRowHandle = -1;
                this.GCGoodsData.DataSource = listMaterial;
            }
            if (billDetail.PayItemList != null)
            {
                for (int i = 0; i < billDetail.PayItemList.Length; i++)
                {
                    WebRef.ESettlementBillPayItem payItem = new WebRef.ESettlementBillPayItem();
                    payItem.PayItemName = billDetail.PayItemList[i].PayItemName;
                    payItem.PayItemId = billDetail.PayItemList[i].PayItemId;
                    payItem.Type = billDetail.PayItemList[i].PayItemType;
                    payItem.Amount = billDetail.PayItemList[i].Amount;
                    listPayItem.Add(payItem);
                }
                this.GCOther.DataSource = null;
                this.GVOther.FocusedRowHandle = -1;
                this.GCOther.DataSource = listPayItem;
            }
        }
        /// <summary>
        /// 获取服务项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.ESettlementBillServiceItem> GetListServiceItem()
        {
            List<WebRef.ESettlementBillServiceItem> listItem = this.GVServiceProject.DataSource as List<WebRef.ESettlementBillServiceItem>;
            return listItem;
        }
        /// <summary>
        /// 获取商品配料
        /// </summary>
        /// <returns></returns>
        private List<WebRef.ESettlementBillMaterial> GetListMaterial()
        {
            List<WebRef.ESettlementBillMaterial> listItem = this.GVGoodsData.DataSource as List<WebRef.ESettlementBillMaterial>;
            return listItem;
        }
        /// <summary>
        /// 获取其他收费/付费项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.ESettlementBillPayItem> GetListPayItem()
        {
            List<WebRef.ESettlementBillPayItem> listItem = this.GVOther.DataSource as List<WebRef.ESettlementBillPayItem>;
            return listItem;
        }
        /// <summary>
        /// 获取套餐服务项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.ESettlementBillPackageItem> GetListPackageItem()
        {
            List<WebRef.ESettlementBillPackageItem> listItem = new List<WebRef.ESettlementBillPackageItem>();
            List<WebRef.ESettlementBillPackageItem> listAll = this.GVPackageItem.DataSource as List<WebRef.ESettlementBillPackageItem>;
            if (listAll != null)
            {
                for (int i = 0; i < listAll.Count; i++)
                {
                    if (listAll[i].UseCount != 0)
                    {
                        listItem.Add(listAll[i]);
                    }
                }
            }
            return listItem;
        }
        /// <summary>
        /// 生成结算单
        /// </summary>
        private void CreateSettleBill(string flag)
        {
            WebRef.ESettlementBill bill = new WebRef.ESettlementBill();
            bill.BusinessId = ModuleContext.Current.BusinessId.Value;
            bill.StationId = ModuleContext.Current.StationId.Value;
            bill.MaintenanceBillId = billDetail.Bill.Id;
            bill.CustomerId = billDetail.Bill.CustomerId;
            bill.AutomobileId = billDetail.Bill.AutomobileId;
            bill.SpendBalance = Convert.ToDecimal(this.txtBalanceAmount.EditValue);
            bill.SpendPoint = Convert.ToDecimal(txtUsedCredits.EditValue);
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<Guid> result = new Service.CreateService().CreateSettlementBill(bill,
                    GetListServiceItem() == null ? null : GetListServiceItem().ToArray(),
                    GetListMaterial() == null ? null : GetListMaterial().ToArray(),
                    GetListPayItem() == null ? null : GetListPayItem().ToArray(),
                    GetListPackageItem() == null ? null : GetListPackageItem().ToArray(), null);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        if (flag.Equals("Settle"))
                        {
                            UIContext.Current.ViewManager.CloseView(true, null);
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ReplaceView(new CheckOut.CheckOutSettlementBillView(result.Data, "Settle"));
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        #endregion

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("back", Resources.isBack, "返回", btnBack_Click))
                .AddAction(new ActionNode("settle", Resources.isSettling, "结算", btnSettle_Click))
                .AddAction(new ActionNode("checked", Resources.isSettling, "结算并收银", btnChecked_Click))
              .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {

            }
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    BindPackageUse();
                    _promise.Resolve();
                }));
            }).Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    BindSettleMentTypes();
                    _promise.Resolve();
                }));
            }).Then(LoadBillInfo)
                .Then(LoadEnabledPackageInstanceList)
                .Then(() =>
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        ClacTotalAmount();
                        _promise.Resolve();
                    }));
                })
                .Run(null);
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("订单结算");
        }
        #endregion

        #region Action
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSettle_Click(object sender, object e)
        {
            string message = null;
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
            }
            else
            {
                CreateSettleBill("Settle");
            }
        }
        /// <summary>
        /// 收银
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChecked_Click(object sender, object e)
        {
            string message = null;
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
            }
            else
            {
                CreateSettleBill("CheckedOut");
            }
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, object e)
        {
            billDetail = null;
            _promise
                .Then(LoadBillInfo)
                .Then(LoadEnabledPackageInstanceList)
                .Run();
        }
        /// <summary>
        /// 服务项目根据输入折扣获取应收金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVServiceProject_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.GVServiceProject.FocusedColumn == e.Column)
            {
                if (e.Column.FieldName == "Discount")
                {
                    WebRef.ESettlementBillServiceItem model = this.GVServiceProject.GetRow(e.Column.View.FocusedRowHandle) as WebRef.ESettlementBillServiceItem;
                    this.GVServiceProject.SetRowCellValue(e.Column.View.FocusedRowHandle, "ActualAmount", model.Amount);
                    ClacTotalAmount();
                }
            }
        }
        /// <summary>
        /// 商品配件根据输入折扣获取应收金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVGoodsData_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.GVGoodsData.FocusedColumn == e.Column)
            {
                if (e.Column.FieldName == "Discount")
                {
                    WebRef.ESettlementBillMaterial model = this.GVGoodsData.GetRow(e.Column.View.FocusedRowHandle) as WebRef.ESettlementBillMaterial;
                    this.GVGoodsData.SetRowCellValue(e.Column.View.FocusedRowHandle, "ActualAmount", model.Amount);
                    ClacTotalAmount();
                }
            }
        }
        /// <summary>
        /// 若使用套餐项目,对应的服务项目结算状态发生改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RILookUpEditUse_EditValueChanged(object sender, EventArgs e)
        {
            WebRef.ESettlementBillPackageItem item = this.GVPackageItem.GetRow(this.GVPackageItem.FocusedRowHandle) as WebRef.ESettlementBillPackageItem;
            if (item.UseCount == 0)
            {
                item.UseCount++;
            }
            else
            {
                item.UseCount = 0;
            }
            if (item.PackageItemType == Domain.Constant.PackageItemTypes.ServiceItem)
            {
                for (int i = 0; i < this.GVServiceProject.RowCount; i++)
                {
                    WebRef.ESettlementBillServiceItem serviceItem = this.GVServiceProject.GetRow(i) as WebRef.ESettlementBillServiceItem;
                    if (serviceItem.ServiceItemId.ToString().Equals(item.PackageItemTagData))
                    {
                        if (item.UseCount == 0)
                        {
                            this.GVServiceProject.SetRowCellValue(i, "SettlementType", Domain.Constant.SettlementTypes.ByPackage);
                        }
                        else
                        {
                            this.GVServiceProject.SetRowCellValue(i, "SettlementType", Domain.Constant.SettlementTypes.ByPay);
                        }
                    }
                }
            }
            ClacTotalAmount();
        }
        #endregion
    }
}
